package service;

import dao.BlacklistDao;
import domin.Blacklist;
import util.Condition;
import util.JdbcHelper;
import util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashSet;

public class BlacklistsService {
    private BlacklistDao blacklistDao = BlacklistDao.getInstance();
    private static BlacklistsService blacklistsService = new BlacklistsService();
    public static BlacklistsService getInstance(){
        return blacklistsService;
    }

    public Collection<Blacklist> findAll(Collection<Condition> condition, Pagination pagination) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Collection<Blacklist> blacklists = blacklistDao.findAll(connection,condition,pagination);
        JdbcHelper.close(connection);
        return blacklists;
    }

    public Collection<Blacklist> getAllWithCondition(String s) throws SQLException{
        Collection<Blacklist>collection = new HashSet<Blacklist>();
        Connection connection = JdbcHelper.getConn();
        Collection<Blacklist> blacklists = BlacklistDao.getInstance().getAllWithCondition(connection,s);
        collection.addAll(blacklists);
        JdbcHelper.close(connection);
        return collection;
    }

    public Blacklist find(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        Blacklist blacklist = blacklistDao.find(connection,id);
        JdbcHelper.close(connection);
        return blacklist;
    }

    public boolean add(Blacklist blacklist) throws SQLException {
        boolean added =false;
        Connection connection = JdbcHelper.getConn();
        connection.setAutoCommit(false);
        try
        {
            added = blacklistDao.add(connection,blacklist);
            connection.commit();
        }
        catch (SQLException e){
            connection.rollback();
        }
        finally {
            connection.setAutoCommit(true);
            JdbcHelper.close(connection);
        }
        return added;
    }

    public boolean delete(Integer id) throws SQLException {
        Connection connection = JdbcHelper.getConn();
        boolean deleted =blacklistDao.delete(connection,id);
        JdbcHelper.close(connection);
        return deleted;
    }
}
